<template>
  <div>
    <!-- 面包屑导航 -->
    <bread />
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索框 -->
          <el-input
            placeholder="请输入内容"
            v-model="pagination.query"
            clearable
            class="input-with-select"
            @clear="getlist"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getlist"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户按钮 -->
        <el-col :span="6">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户信息列表 -->
      <el-table :data="list" border style="width: 100%">
        <el-table-column type="index" label="#" width="50"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="150">
        </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话" width="150">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" width="100">
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template v-slot="data">
            <el-switch
              v-model="data.row.mg_state"
              @change="state(data.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="data">
            <!-- 修改用户按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="updata(data.row)"
            ></el-button>
            <!-- 删除用户按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="del(data.row.id)"
            ></el-button>
            <!-- 分配权限按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配权限"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="getrole(data.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="pagination.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 添加用户弹出框 -->
      <el-dialog title="添加用户" :visible.sync="dialogVisible" width="30%">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="ruleForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="ruleForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="adduser">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
    <!-- 修改用户信息弹框 -->
    <el-dialog title="编辑用户" :visible.sync="updataVisible" width="30%">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updataVisible = false">取 消</el-button>
        <el-button type="primary" @click="upuser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配用户权限 -->
    <el-dialog title="提示" :visible.sync="roleVisible" width="30%">
      <p>当前的用户:{{ namelist.username }}</p>
      <p>当前的角色:{{ namelist.role_name }}</p>
      <p>
        分配新的角色:
        <el-select v-model="select" slot="prepend" placeholder="请选择">
          <el-option
            v-for="item in rolelist.data"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleVisible = false">取 消</el-button>
        <el-button type="primary" @click="roleAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import bread from "../bread";
export default {
  
  data() {
    // 手机号正则表达式
    var checkMobile = (rule, value, cd) => {
      let re = /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/;
      if (re.test(value)) {
        cd();
      } else {
        cd(new Error("电话格式不正确"));
      }
    };
    return {
      list: [], //用户列表
      pagination: {
        query: "",
        pagenum: 1, //当前页码
        pagesize: 2, //每页显示条数
      },
      total: 0, //所有数据条数
      dialogVisible: false, //添加新用户弹框
      updataVisible: false, //修改用户弹窗
      roleVisible: false, //修改用户角色权限弹窗
      ruleForm: {
        //添加用户信息
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      rolelist: [],
      select: "",
      namelist: [],
      // 正则表达式
      rules: {
        //用户名正则
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 10, message: "长度在 2 到 5 个字符", trigger: "blur" },
        ],
        // 密码正则
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        // 邮箱正则
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur"] },
        ],
        // 手机正则
        mobile: [
          { required: true, message: "请输入电话号", trigger: "blur" },
          {
            validator: checkMobile,
            message: "请输入正确的手机号",
            trigger: ["blur"],
          },
        ],
      },
    };
  },
  created() {
    this.getlist();
  },
  methods: {
    //   获取用户信息
    getlist() {
      this.axios.get("/users", { params: this.pagination }).then((res) => {
        let { data } = res.data;
        this.total = data.total;
        this.list = data.users;
      });
    },
    //当前页的条数
    handleSizeChange(val) {
      this.pagination.pagesize = val;
      this.getlist();
    },
    //当前页数
    handleCurrentChange(val) {
      this.pagination.pagenum = val;
      this.getlist();
    },
    //添加新用户
    adduser() {
      this.$refs.ruleForm.validate((vali) => {
        if (vali) {
          this.axios.post("/users", this.ruleForm).then((res) => {
            let { data } = res;
            console.log(data);
            if (data.meta.status == 201) {
              this.$message.success(data.meta.msg);
              this.dialogVisible = false;
              this.ruleForm={}
              this.getlist();
            } else {
              this.$message.error(data.meta.msg);
            }
          });
        }
      });
    },
    // 表单重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible = false;
    },
    //修改用户信息
    updata(data) {
      this.updataVisible = true;
      this.ruleForm = data;
    },
    //保存编辑用户信息
    upuser() {
      this.$refs.ruleForm.validate((vali) => {
        if (vali) {
          let res = this.axios(`users/${this.ruleForm.id}`).then((res) => {
            let { meta } = res.data;
            if (meta.status == !200) {
              this.$message.error(meta.msg);
            } else {
              this.$message.success(meta.msg);
              this.updataVisible = false;
            }
          });
        }
      });
    },
    // 分配用户权限
    async getrole(list) {
      this.namelist = list;
      this.roleVisible = true;
      let res = await this.axios.get("roles");
      let { data, meta } = res;
      this.rolelist = data;
    },
    //保存分配角色权限
    async roleAdd() {
      if (this.select == "") {
        this.$message.error("请选择要分配的新角色！");
      } else {
        let res = await this.axios.put(`users/${this.namelist.id}/role`, {
          rid: this.namelist.id,
        });
        let { meta } = res.data;
        if (meta.status !== 200) {
          this.$message.error(meta.msg);
        } else {
          this.$message.success(meta.msg);
          this.roleVisible = false;
          this.select = "";
        }
      }
    },
    //删除用户
    del(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.axios.delete(`users/${id}`).then((res) => {
            let { meta } = res.data;
            if (meta.status !== 200) {
              this.$message.error(meta.msg);
            } else {
              this.$message({
                type: "success",
                message: "删除成功!",
              }); 
              this.getlist();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //修改用户状态
    async state(info) {
      let res = await this.axios.put(`users/${info.id}/state/${info.mg_state}`);
      if (res.data.meta.status !== 200) {
        row.mg_state = !row.mg_state;
        this.$message.error("修改状态失败");
      }
      this.$message.success(res.data.meta.msg);
    },
    // 搜索用户信息
  },
  components: {
    bread,
  },
};
</script>
<style lang="scss">
.el-breadcrumb {
  margin-bottom: 10px;
}
.el-table {
  margin-top: 20px;
}
.el-table__header tr,
.el-table__header th {
  padding: 0;
  height: 80px;
  text-align: center;
}
.el-table__body tr,
.el-table__body td {
  padding: 0;
  height: 60px;
  text-align: center;
}
p {
  margin: 15px 0;
}
</style>